import React, { useState, useEffect, useMemo } from 'react';
import { Link } from 'react-router-dom';
import Form from '@knownsec/react-component/dist/Form';
import Select from '@knownsec/react-component/dist/Select';
import Input from '@knownsec/react-component/dist/Input';
import Button from '@knownsec/react-component/dist/Button';
import Checkbox from '@knownsec/react-component/dist/Checkbox';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import Radio from '@knownsec/react-component/dist/Radio';
import Datetime from '@knownsec/react-component/dist/Datetime';
import { TimePicker } from 'antd';
import moment from 'moment';
import recursion from '../../../helpers/recursionFormJob';
import Helper from '../../../components/Helper';
import CollectFrequency from '../../../components/CollectFrequency';
import {
	SSL_CATEGORY_KEY_LABEL_MAP,
	SECURITY_EVENT_TYPE_MAP,
	CONTENT_KEYWORD_TYPES,
	CONTENT_PRIVACY_DISCLOSURE_TYPES,
	FREQ_UNIT_MAP,
	NODE_ID_LABEL_MAP2,
	FREQUENCY_NUMBERS,
	WEAKNESS_FREQUENCY_UNIT_MAP,
	FREQUENCY_UNIT_MAP,
} from '../../../../common/constants';
import pathOr from 'ramda/es/pathOr';
import s from '../style.module.css';
import cn from 'classnames';
import Message from '@knownsec/react-component/dist/Message';
import { getTaskEnable, checkHttps } from './unit';

const TASK_SETTINGS_NAME_MAP = {
	vul: 'vul_settings',
	ssl: 'ssl_settings',
	content: 'content_settings',
	securityEvent: 'security_event_settings',
	changeCheck: 'change_check_settings',
};

const TASK_CN_NAME_MAP = {
	vul: 'Web漏洞监测',
	ssl: 'SSL安全监测',
	content: '内容违规监测',
	securityEvent: '安全事件监测',
	changeCheck: '篡改监测',
};

function WebStep1({
	data,
	jid,
	atid,
	assetType,
	scheduleJobList,
	scheduleJobMap,
	manualJobList,
	manualJobMap,
	setBtnType,
}) {
	const resD = JSON.parse(sessionStorage.resD);
	const form = Form.useFormInstance();
	// form?.setFieldsValue(data)
	const vulEnable =
		Form.useWatch(['vul_settings', 'enable'], form) ||
		data?.vul_settings?.enable;
	const sslEnable =
		Form.useWatch(['ssl_settings', 'enable'], form) ||
		data?.ssl_settings?.enable;
	const securityEnable =
		Form.useWatch(['security_event_settings', 'enable'], form) ||
		data?.security_event_settings?.enable;
	const contentEnable =
		Form.useWatch(['content_settings', 'enable'], form) ||
		data?.content_settings?.enable;
	const changeCheckEnable =
		Form.useWatch(['change_check_settings', 'enable'], form) ||
		data?.change_check_settings?.enable;
	const triggerType = Form.useWatch('trigger_type', form);
	const { startType, periodStartTime, periodEndTime, startAt } =
		Form.useWatch('ws_task_time', form) || {};
	const jobIds = Form.useWatch('job_ids', form);
	const [timeTip, setTimeTip] = useState(null);
	const [errorData, setErrorData] = useState({});
	const isSupportWsTime =
		pathOr(0, ['feature', 'wsTaskTime'], resD) &&
		pathOr(0, ['balance', 'wsTaskTime', 'total'], resD) > 0;
	const validatormap = async (rule, value, callback) => {
		if (rule.field === 'job_ids') {
			if (!value[0]) {
				setErrorData({ type: 'error', message: '请选择资产地址' });
				return Promise.reject();
			} else {
				setErrorData({});
			}
		}
		if (rule.field === 'name') {
			if (!value || !value.trim()) {
				return Promise.reject('请输入任务名称');
			} else if (
				!(
					value.trim().replace(/[a-zA-Z0-9_\u4E00-\u9FA5]{1,50}/g, '')
						.length === 0
				)
			) {
				return Promise.reject(
					'名称格式错误，只能输入1～50个中文、英文字母、数字、下划线'
				);
			}
			// eslint-disable-next-line prefer-promise-reject-errors
		}
		if (rule.field.split('.')[1] === 'enable') {
			if (
				!vulEnable &&
				!sslEnable &&
				!securityEnable &&
				!contentEnable &&
				!changeCheckEnable
			) {
				Message.show({ type: 'error', message: '请选择监测项' });
				return Promise.reject();
			}
		}
		if (
			['ws_task_time.periodStartTime', 'ws_task_time.periodEndTime'].includes(
				rule.field
			)
		) {
			if (periodStartTime && periodEndTime) {
				setTimeTip(null);
				let diffM = moment(periodEndTime, 'HH:mm:ss').diff(
					moment(periodStartTime, 'HH:mm:ss'),
					'minutes'
				);
				diffM = diffM < 0 ? diffM + 24 * 60 : diffM;
				if (diffM > 18 * 60) {
					setTimeTip({
						type: 'error',
						message: '时间段最大范围为18小时，请重新选择',
					});
					return Promise.reject();
				}
				if (diffM < 6 * 60) {
					setTimeTip({
						type: 'error',
						message: '时间段最小范围为6小时，请重新选择',
					});
					return Promise.reject();
				}
			}
		}
		if (rule.field === 'ws_task_time.startType') {
			if (!startAt && value === 'time') {
				setTimeTip({ type: 'error', message: '请选择定时执行时间' });
				return Promise.reject();
			} else {
				return Promise.resolve();
			}
		}
		return Promise.resolve();
	};
	useEffect(() => {
		form?.setFieldsValue(data);
		setTimeTip(null);
		document
			?.getElementsByClassName('jobIdScheduleSelect')[0]
			?.getElementsByClassName('rc-input-content')[0]
			?.setAttribute(
				'placeholder',
				'请输入搜索内容，已过滤下发过周期性任务的资产'
			);
		document
			?.getElementsByClassName('jobIdManualSelect')[0]
			?.getElementsByClassName('rc-input-content')[0]
			?.setAttribute('placeholder', '请输入搜索内容');
	}, [data]);

	const getSelectAssetForm = () => {
		const classNameString =
			triggerType === 'schedule' ? 'jobIdScheduleSelect' : 'jobIdManualSelect';
		const jobList =
			triggerType === 'schedule' && !atid ? scheduleJobList : manualJobList;
		const typeString = triggerType !== 'schedule' ? { type: 'array' } : {};
		return (
			<Form.Item
				label="资产地址"
				name="job_ids"
				validateStatus={errorData?.type}
				extra={
					errorData?.message ? (
						<span className="danger-color">请选择资产地址</span>
					) : (
						<span></span>
					)
				}
				rules={[{ required: true, validator: validatormap }]}
				{...typeString}
			>
				<Select
					placeholder="请选择资产地址"
					className={cn(
						s.w90p,
						s.jobIdSelect,
						`${classNameString}`,
						atid && s.disw100p
					)}
					option={jobList}
					checkAll
					multiple
					searchable
					clearable
					disabled={atid}
				/>
			</Form.Item>
		);
	};
	const taskTypeName = taskType => {
		const helperMap = {
			ssl: '仅https资产支持SSL安全监测。',
			securityEvent: '持续监测暗链、风险外链、挖矿、挂马等篡改事件。',
		};
		const settingsName = pathOr('', [taskType], TASK_SETTINGS_NAME_MAP);
		const nameCn = pathOr('', [taskType], TASK_CN_NAME_MAP);
		const helper = pathOr('', [taskType], helperMap);
		const enableType = getTaskEnable(taskType, triggerType);
		let hasHttps = true;
		if (taskType === 'ssl') {
			hasHttps = checkHttps(manualJobMap, jobIds);
		}
		let toolTipOverlay = '请先升级套餐服务';
		if (taskType === 'ssl' && enableType && !hasHttps) {
			toolTipOverlay = '仅https资产支持SSL安全监测';
		}
		return (
			<div className={cn(s.pr, s.w165)}>
				<Form.Item
					labelAlign="left"
					labelCol={{ span: 0 }}
					wrapperCol={{ span: 24 }}
					valuePropName="checked"
					rules={[{ validator: validatormap }]}
					name={[`${settingsName}`, 'enable']}
				>
					{enableType && hasHttps ? (
						<Checkbox>{nameCn}</Checkbox>
					) : (
						<Tooltip overlay={toolTipOverlay} placement="top">
							<span>
								<Checkbox disabled>{nameCn}</Checkbox>
							</span>
						</Tooltip>
					)}
				</Form.Item>
				{helper && (
					<Helper
						className={cn(s.itemHelp, s.r31)}
						placement="top"
						overlay={helper}
					/>
				)}
			</div>
		);
	};

	const manualTaskTimes = taskType => {
		const perMonthTimes = pathOr(
			0,
			['balance', `${taskType}ManualTask`, 'total'],
			resD
		);
		const existMonthTimes =
			perMonthTimes -
			pathOr(0, ['balance', `${taskType}ManualTask`, 'used'], resD);
		return (
			<div
				className={s.webTipsBox}
				style={{ display: triggerType === 'manual' ? 'flex' : 'none' }}
			>
				<svg
					t="1632473432354"
					className="icon"
					viewBox="0 0 1024 1024"
					version="1.1"
					xmlns="http://www.w3.org/2000/svg"
					p-id="2936"
					width="16"
					height="16"
				>
					<path
						d="M512 64c247.04 0 448 200.96 448 448s-200.96 448-448 448S64 759.04 64 512 264.96 64 512 64z m0 64.277333C300.416 128.277333 128.298667 300.416 128.298667 512c0 211.541333 172.117333 383.701333 383.701333 383.701333 211.541333 0 383.701333-172.16 383.701333-383.701333 0-211.584-172.16-383.701333-383.701333-383.701333z m0 586.730667a48 48 0 1 1 0 96 48 48 0 0 1 0-96zM512 234.666667a32 32 0 0 1 32 32v341.333333a32 32 0 0 1-64 0v-341.333333A32 32 0 0 1 512 234.666667z"
						p-id="2937"
						fill="#ffad41"
					></path>
				</svg>
				每月{perMonthTimes}次，当月剩余{existMonthTimes || 0}次
			</div>
		);
	};

	const scheduleTaskFreq = taskType => {
		const settingsName = pathOr('', [taskType], TASK_SETTINGS_NAME_MAP);
		// 值改变，react每次会重新渲染页面，以下map值也会跟着修改
		const enbaleMap = {
			vul: vulEnable,
			ssl: sslEnable,
			content: contentEnable,
			securityEvent: securityEnable,
			changeCheck: changeCheckEnable,
		};
		const taskTypeUnitMap =
			taskType === 'securityEvent'
				? FREQUENCY_UNIT_MAP
				: WEAKNESS_FREQUENCY_UNIT_MAP;
		const formEnable = pathOr(false, [taskType], enbaleMap);
		return (
			<div
				className={cn(s.df, s.aic, s.pr, s.t6)}
				style={{ display: triggerType === 'manual' ? 'none' : 'flex' }}
			>
				<Form.Item
					className={cn(s.flex1, s.h42)}
					label="监测频率"
					labelAlign="left"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}
					name={[settingsName, 'interval']}
				>
					<CollectFrequency
						disabled={!formEnable}
						maxFreq={pathOr(
							0,
							['balance', `${taskType}MaxFreq`, 'total'],
							resD
						)}
						numbers={FREQUENCY_NUMBERS}
						unitMap={pathOr({}, [taskType], taskTypeUnitMap)}
					/>
				</Form.Item>
			</div>
		);
	};

	return (
		<>
			<Form
				form={form}
				pro
				initialValues={data}
				onValuesChange={(newItem, allValues) => {
					const val = recursion(newItem);
					console.log(newItem, allValues);
					form.setFieldsValue(val);
				}}
				labelAlign="right"
				labelCol={{ span: 3 }}
				wrapperCol={{ span: 20, offset: 1 }}
				name="webStep1"
			>
				<div className={s.jobContent}>
					<div
						style={{
							width: '876px',
							margin: '0 auto',
							paddingBottom: '1.5rem',
						}}
					>
						<Form.Item label="任务类型" name="trigger_type">
							<Radio.Group>
								<Radio className={s.h24} value={'schedule'} disabled={atid}>
									周期性任务
								</Radio>
								<Radio
									refs="taskTriggerTypeManual"
									className={cn(s.ml24, s.h24)}
									value={'manual'}
									disabled={atid}
								>
									单次任务
								</Radio>
							</Radio.Group>
						</Form.Item>
						<Form.Item
							label="任务名称"
							name="name"
							rules={[{ required: true, validator: validatormap }]}
						>
							<Input
								placeholder="请输入任务名称"
								className={cn(s.w90p)}
								maxLength="50"
							/>
						</Form.Item>
						<div className={cn(s.pr, s.jobIdSelect)}>
							{getSelectAssetForm()}
							{!atid && (
								<Link
									to={`/asset-manage/manage/${
										assetType === 'host' ? 'host' : 'web'
									}`}
									className={cn(s.toJob)}
									style={{ right: '8px', top: '18px' }}
								>
									添加资产
								</Link>
							)}
						</div>
						{assetType === 'web' && (
							<div
								className={cn(
									s.taskItems,
									s.noTips,
									triggerType !== 'manual' && s.mt_10
								)}
							>
								<Form.Item label="监测项">
									<div className={cn(s.df, s.aic, s.pr)}>
										{taskTypeName('vul')}
										{manualTaskTimes('vul')}
										{scheduleTaskFreq('vul')}
									</div>
								</Form.Item>
								<Form.Item
									labelCol={{ span: 0 }}
									wrapperCol={{ span: 24, offset: 4 }}
								>
									<div className={cn(s.df, s.aic)}>
										{taskTypeName('ssl')}
										{manualTaskTimes('ssl')}
										{scheduleTaskFreq('ssl')}
									</div>
								</Form.Item>
								<Form.Item
									labelCol={{ span: 0 }}
									wrapperCol={{ span: 24, offset: 4 }}
								>
									<div className={cn(s.df, s.aic)}>
										{taskTypeName('securityEvent')}
										{manualTaskTimes('securityEvent')}
										{scheduleTaskFreq('securityEvent')}
									</div>
								</Form.Item>
								<Form.Item
									labelCol={{ span: 0 }}
									wrapperCol={{ span: 24, offset: 4 }}
								>
									<div className={cn(s.df, s.aic)}>
										{taskTypeName('content')}
										{manualTaskTimes('content')}
										{scheduleTaskFreq('content')}
									</div>
								</Form.Item>
								{triggerType === 'schedule' && (
									<Form.Item
										labelCol={{ span: 0 }}
										wrapperCol={{ span: 24, offset: 4 }}
									>
										<div className={cn(s.df, s.aic)}>
											{taskTypeName('changeCheck')}
											{scheduleTaskFreq('changeCheck')}
										</div>
									</Form.Item>
								)}
								{isSupportWsTime && (
									<Form.Item
										validateStatus={timeTip?.type}
										extra={
											timeTip?.message ? (
												<span
													className={cn('danger-color', {
														[s.timeTip]: triggerType === 'manual',
													})}
												>
													{timeTip?.message}
												</span>
											) : (
												<span></span>
											)
										}
										colon={false}
										className={triggerType === 'manual' ? '' : 'mt20'}
										label={
											<span
												className="df aic mt10 pr"
												style={{ right: '-3px' }}
											>
												<span>
													{triggerType === 'manual' ? '执行方式' : '监测时间段'}
												</span>
												{triggerType !== 'manual' && (
													<Helper
														placement="top"
														overlay="任务将在监测时间段内进行监测，超过配置时间段未执行的资产当前周期将停止监测。"
													/>
												)}
												:
											</span>
										}
									>
										<div className={cn(s.df, s.aic, s.pr)}>
											<div
												className={cn('df aic pt5')}
												style={{
													display: triggerType === 'manual' ? 'flex' : 'none',
												}}
											>
												<Form.Item
													className={cn(s.h42)}
													label=""
													labelAlign="left"
													labelCol={{ span: 0 }}
													wrapperCol={{ span: 24 }}
													name={['ws_task_time', 'startType']}
													rules={[{ validator: validatormap }]}
												>
													<Radio.Group>
														<Radio className={s.h24} value={'now'}>
															立即执行
														</Radio>
														<Radio className={cn(s.ml24, s.h24)} value={'time'}>
															定时执行
														</Radio>
													</Radio.Group>
												</Form.Item>
												<Form.Item
													className={cn(s.flex1)}
													label=""
													labelAlign="left"
													labelCol={{ span: 0 }}
													wrapperCol={{ span: 24 }}
													name={['ws_task_time', 'startAt']}
												>
													<Datetime
														placeholder="请选择定时执行时间"
														style={{ top: '-6px' }}
														className="pr"
														disabled={startType === 'now'}
													/>
												</Form.Item>
											</div>
											<div
												className={cn(s.df, s.aic, 'mt5')}
												style={{
													display: triggerType === 'manual' ? 'none' : 'flex',
												}}
											>
												<Form.Item
													className={cn(s.flex1, s.h42)}
													label=""
													labelAlign="left"
													labelCol={{ span: 0 }}
													wrapperCol={{ span: 24 }}
													name={['ws_task_time', 'periodStartTime']}
													rules={[{ validator: validatormap }]}
												>
													<TimePicker format={'HH:mm'} placeholder="开始时间" />
												</Form.Item>
												<span className={cn('ml16 mr16', s.h42)}>~</span>
												<Form.Item
													className={cn(s.flex1, s.h42)}
													label=""
													labelAlign="left"
													labelCol={{ span: 0 }}
													wrapperCol={{ span: 24 }}
													name={['ws_task_time', 'periodEndTime']}
													rules={[{ validator: validatormap }]}
												>
													<TimePicker format={'HH:mm'} placeholder="结束时间" />
												</Form.Item>
											</div>
										</div>
									</Form.Item>
								)}
							</div>
						)}
						{assetType === 'host' && (
							<div className={s.hostCollect}>
								<Form.Item label="监测频率" name="interval">
									<CollectFrequency
										maxFreq={pathOr(
											0,
											['balance', 'hostVulMaxFreq', 'total'],
											resD
										)}
									/>
								</Form.Item>
								{pathOr(0, ['feature', 'wsTaskTime'], resD) &&
									pathOr(0, ['balance', 'wsTaskTime', 'total'], resD) && (
										<Form.Item
											validateStatus={timeTip?.type}
											extra={
												timeTip?.message ? (
													<span
														className={cn('danger-color', {
															[s.timeTip]: triggerType === 'manual',
														})}
													>
														{timeTip?.message}
													</span>
												) : (
													<span></span>
												)
											}
											colon={false}
											className={triggerType === 'manual' ? '' : 'mt20'}
											label={
												<span
													className="df aic mt10 pr"
													style={{ right: '-3px' }}
												>
													<span>
														{triggerType === 'manual'
															? '执行方式'
															: '监测时间段'}
													</span>
													{triggerType !== 'manual' && (
														<Helper
															placement="top"
															overlay="任务将在监测时间段内进行监测，超过配置时间段未执行的资产当前周期将停止监测。"
														/>
													)}
													:
												</span>
											}
										>
											<div className={cn(s.df, s.aic, s.pr)}>
												<div
													className={cn('df aic pt5')}
													style={{
														display: triggerType === 'manual' ? 'flex' : 'none',
													}}
												>
													<Form.Item
														className={cn(s.h42)}
														label=""
														labelAlign="left"
														labelCol={{ span: 0 }}
														wrapperCol={{ span: 24 }}
														name={['ws_task_time', 'startType']}
														rules={[{ validator: validatormap }]}
													>
														<Radio.Group>
															<Radio className={s.h24} value={'now'}>
																立即执行
															</Radio>
															<Radio
																className={cn(s.ml24, s.h24)}
																value={'time'}
															>
																定时执行
															</Radio>
														</Radio.Group>
													</Form.Item>
													<Form.Item
														className={cn(s.flex1)}
														label=""
														labelAlign="left"
														labelCol={{ span: 0 }}
														wrapperCol={{ span: 24 }}
														name={['ws_task_time', 'startAt']}
													>
														<Datetime
															placeholder="请选择定时执行时间"
															style={{ top: '-6px' }}
															className="pr"
															disabled={startType === 'now'}
														/>
													</Form.Item>
												</div>
												<div
													className={cn(s.df, s.aic, 'mt5')}
													style={{
														display: triggerType === 'manual' ? 'none' : 'flex',
													}}
												>
													<Form.Item
														className={cn(s.flex1, s.h42)}
														label=""
														labelAlign="left"
														labelCol={{ span: 0 }}
														wrapperCol={{ span: 24 }}
														name={['ws_task_time', 'periodStartTime']}
														rules={[{ validator: validatormap }]}
													>
														<TimePicker
															format={'HH:mm'}
															placeholder="开始时间"
														/>
													</Form.Item>
													<span className={cn('ml16 mr16', s.h42)}>~</span>
													<Form.Item
														className={cn(s.flex1, s.h42)}
														label=""
														labelAlign="left"
														labelCol={{ span: 0 }}
														wrapperCol={{ span: 24 }}
														name={['ws_task_time', 'periodEndTime']}
														rules={[{ validator: validatormap }]}
													>
														<TimePicker
															format={'HH:mm'}
															placeholder="结束时间"
														/>
													</Form.Item>
												</div>
											</div>
										</Form.Item>
									)}
							</div>
						)}
					</div>
				</div>
			</Form>
			<div className="tac mt16">
				<Button
					type="default"
					htmlType="button"
					onClick={e => {
						e.preventDefault();
						console.log('');
						window.history.back();
					}}
				>
					取消
				</Button>
				<Button
					type="plain"
					htmlType="submit"
					style={{ margin: '0 24px' }}
					onClick={() => setBtnType('下一步')}
				>
					下一步
				</Button>
				<Button
					type="primary"
					style={{ position: 'relative', top: '-1px' }}
					onClick={() => setBtnType(atid ? '保存配置' : '下发任务')}
				>
					{atid ? '保存配置' : '下发任务'}
				</Button>
			</div>
		</>
	);
}
export default WebStep1;
